let app = getApp();
const { getUserInfo } = require('../../../common/utils/ws/wsxcx-opendata-sdk');

Page({

  data: {
    isShow: false,
    isHave: false
  },

  onLoad: function (options) {
    let that = this;
    that.setData({
      id: options.id
    }, () => {
      that.checkAuthorize();
    })
  },

  checkAuthorize () {
    let that = this;
    let { id } = that.data;
    getUserInfo()
      .then(userInfo => {
        app.util.request({
          data: { id },
          url: 'wechatWork/redpacket/getActivity',
          success: (res) => {
            console.log("红包接口：", res)
            let { errno, data: { is_open, activity } } = res.data
            if (Number(errno) === 0 && Number(is_open) === 0) {
              that.setData({
                userInfo,
                isHave: true,
                isShow: false,
                ...activity
              })
            } else {
              const path = '/common/page/redEnvelopes/detail'
              app.util.navigateTo(path, { id }, true);
            }
          }
        })
      })
      .catch(res => {
        this.setData({
          isShow: true,
        });
      });
  },

  getUserInfo (e) {
    this.checkAuthorize();
  },

  fire () {
    wx.showLoading({
      title: '处理中...',
      mask: true,
    });
    let { id } = this.data;
    app.util.request({
      data: { id },
      url: 'wechatWork/redpacket/openRedpacket',
      success: (res) => {
        let { errno, message } = res.data
        if (Number(errno) === 0) {
          const path = '/common/page/redEnvelopes/detail'
          app.util.navigateTo(path, { id }, true);
        } else {
          wx.showToast({
            title: message || '领取失败！',
            icon: 'none',
            duration: 2000,
            mask: true,
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '领取失败！',
          icon: 'none',
          duration: 2000,
          mask: true,
        });
      }
    })
  },
})